package com.mgs.product.tagger.handlers
{
	import com.mgs.fwk.context.ApplicationContext;
	import com.mgs.fwk.handlers.ActionHandler;
	import com.mgs.product.tagger.controller.ContextController;
	import com.mgs.product.tagger.actions.ApplicationAction;
	import com.mgs.product.tagger.actions.DeleteAxisAction;
	import com.mgs.product.tagger.model.Classifiable;
	import com.mgs.product.tagger.model.Segment;
	import com.mgs.product.tagger.ui.dto.AxisUI;
	import com.mgs.product.tagger.ui.dto.NavigationContext;
	
	public class DeleteAxisHandler implements ActionHandler
	{
		public function DeleteAxisHandler()
		{
		}
		
		public function execute(context:ApplicationContext, action:ApplicationAction):void
		{
			var axis:AxisUI = (action as DeleteAxisAction).axis;
			var ctx:NavigationContext = context as NavigationContext;
			ctx.invalidateActiveTags();
			
			var segment:Segment;
			
			// remove each segments
			for each(segment in axis.axis.segments)
			{
				removeSegment(ctx, segment);
			}
			
			// remove the axis.
			if(axis.axis.tags.length == 0)
			{
				// from classification if not tagged
				ctx.classification.elements.splice(ctx.classification.elements.indexOf(axis.axis), 1);
			}
			else
			{
				// from each tags if tagged
				for each(segment in axis.axis.tags)
				{
					segment.taggedElements.splice(segment.taggedElements.indexOf(axis.axis), 1);
				}
				axis.axis.tags = new Vector.<Segment>();
			}
			
		}
		
		private function removeSegment(ctx:NavigationContext, segment:Segment):void
		{
			// if is in active tags ... remove and invalidate
			var index:int = ctx.activeTags.indexOf(segment);
			if(index >= 0)
			{
				ctx.activeTags.splice(index, 1);
				ctx.invalidateActiveTags();
			}
			// untag
			for each(var element:Classifiable in segment.taggedElements)
			{
				element.tags.splice(element.tags.indexOf(segment), 1);
				if(element.tags.length == 0)
				{
					ctx.classification.elements.push(element);
				}
			}
			segment.taggedElements = new Vector.<Classifiable>();
		}
		
	}
}